package com.dxq.test.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.blankj.utilcode.util.ToastUtils;
import com.dxq.test.common.AppManager;
import com.dxq.test.common.Constant;
import com.dxq.test.R;
import com.dxq.test.db.TablesDao;
import com.google.zxing.client.android.MNScanManager;
import com.google.zxing.client.android.other.MNScanCallback;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: zsh
 * Date: 2023/11/1
 * Describe: 二维码扫描页面
 */
public class ScanQRCodeActivity extends AppCompatActivity implements View.OnClickListener {

    public TablesDao tablesDao;

    private ImageView ivBack;
    private Button btnScan;
    private TextView tvTitle, tvPasture, tvYear, tvCode;

    private String sex = "";
    private String breedingStatus = "";
    private String QRCodeID = "";
    private int type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_scan_code);
        tablesDao = new TablesDao(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在appManager结束当前activity
        AppManager.getAppManager().finishActivity(this);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("扫一扫");

        tvPasture = findViewById(R.id.tvPasture);
        tvYear = findViewById(R.id.tvYear);
        tvCode = findViewById(R.id.tvCode);
        btnScan = findViewById(R.id.btnScan);

        btnScan.setOnClickListener(this);
        ivBack.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                ScanQRCodeActivity.this.finish();
                break;

            case R.id.btnScan:
                scanQRCode();
                break;
        }
    }


    /**
     * 跳转到扫码界面扫码
     */
    private void scanQRCode() {
        //申请相机权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        //申请文件(相册)读写权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        //二维码扫码
        //然后通过Intent机制启动zxing框架的CaptureActivity，请求返回结果
//        Intent intent = new Intent(this, CaptureActivity.class);
//        startActivityForResult(intent, Constant.REQ_QR_CODE);
        // 开启扫描
        MNScanManager.startScan(this, new MNScanCallback() {
            public void onActivityResult(int resultCode, Intent data) {
                switch (resultCode) {
                    case MNScanManager.RESULT_SUCCESS:
                        String resultSuccess = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
                        ToastUtils.showShort(resultSuccess);
                        showData(resultSuccess, true);
                        break;
                    case MNScanManager.RESULT_FAIL:
                        // 错误提示：比如：初始化相机失败等
                        String resultError = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR);
                        ToastUtils.showShort(resultError);
                        showData(resultError, false);
                        break;
                    case MNScanManager.RESULT_CANCLE:
                        ToastUtils.showShort("取消扫码");
                        showData("取消扫码", false);
                        break;
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                //摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //获得授权
                    scanQRCode();
                } else {
                    //被禁止授权
                    Toast.makeText(this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;

            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                //文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //获得授权
                    scanQRCode();
                } else {
                    //被禁止授权
                    Toast.makeText(this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void showData(String result, boolean b) {
        if (b) {
            if (null == result || result.length() < 8) {
                tvPasture.setText("");
                tvYear.setText("");
                ToastUtils.showShort("扫描数据异常");
                return;
            }
            if (checkStr(result)) {
                tvPasture.setText("厂家：" + result.substring(0, 4));
                tvYear.setText("年月：" + result.substring(4, 8));
                tvCode.setText("编号：" + result.substring(8));
            } else {
                ToastUtils.showShort("扫描数据无法解析");
                tvPasture.setText("");
                tvYear.setText("");
                tvCode.setText("");
            }
        } else {
            tvPasture.setText("");
            tvYear.setText("");
            tvCode.setText("");
        }
    }

    /**
     * 纯数字校验
     * @param input
     * @return
     */
    private boolean checkStr(String input) {
        String regex = "\\d+";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        if (matcher.matches()) {
            // 匹配成功的处理逻辑
            return true;
        } else {
            // 匹配失败的处理逻辑
            return false;
        }
    }
}
